package com.fallsvc.onlinemusic.config;

import com.fallsvc.onlinemusic.tools.Constant;
import com.fallsvc.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;

/**
 * @auther falls_vc
 * description:
 * @date 2025/4/20  10:35
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1.检查是否登录
        HttpSession session=request.getSession(false);
        if(session==null||session.getAttribute(Constant.USERINFO_SESSION_KEY)==null){
            log.info("用户未登录");
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(401);
            String msg="用户未登录";
            response.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8));
            log.warn(msg);
            return false;
        }
        return true;
    }
}
